package com.tucc.hello.leetcode.no801_1200.no1190;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.reverseParentheses("(i(l(oasv)e)u)"));
    }


    public String reverseParentheses(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        dealReverse(s, 0, false, stringBuilder);
        return stringBuilder.toString();
    }

    public int dealReverse(String s, int index, boolean reverse, StringBuilder resultBuilder){
        while(index < s.length()){
            char ch = s.charAt(index);
            if(ch == '('){
                StringBuilder nextBuilder = new StringBuilder();
                index = dealReverse(s, index + 1, !reverse, nextBuilder);
                if(reverse){
                    resultBuilder.insert(0, nextBuilder);
                }
                else{
                    resultBuilder.append(nextBuilder);
                }
            }
            else if(ch == ')'){
                return index;
            }
            else{
                if(reverse){
                    int tempIndex = index + 1;
                    StringBuilder tempBuilder = new StringBuilder();
                    tempBuilder.append(ch);
                    while(tempIndex < s.length()){
                        char tempCh = s.charAt(tempIndex);
                        if(tempCh == '(' || tempCh == ')'){
                            break;
                        }
                        else{
                            tempBuilder.append(tempCh);
                            tempIndex ++;
                        }
                    }
                    index = tempIndex - 1;
                    resultBuilder.insert(0, tempBuilder.reverse());
                }
                else{
                    resultBuilder.append(ch);
                }
            }
            index ++;
        }
        return index;
    }

}
